<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>咨询商家 - 助农购物</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .chat-container {
            max-width: 1200px;
            margin: 20px auto;
            height: calc(100vh - 200px);
            display: flex;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            overflow: hidden;
        }
        .chat-sidebar {
            width: 300px;
            border-right: 1px solid #dee2e6;
            background-color: #f8f9fa;
            overflow-y: auto;
        }
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .chat-header {
            padding: 15px 20px;
            border-bottom: 1px solid #dee2e6;
            background-color: #fff;
        }
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f8f9fa;
        }
        .chat-input-area {
            padding: 15px 20px;
            border-top: 1px solid #dee2e6;
            background-color: #fff;
        }
        .message {
            margin-bottom: 15px;
            display: flex;
        }
        .message.user {
            justify-content: flex-end;
        }
        .message.merchant {
            justify-content: flex-start;
        }
        .message-content {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 8px;
            word-wrap: break-word;
        }
        .message.user .message-content {
            background-color: #007bff;
            color: white;
        }
        .message.merchant .message-content {
            background-color: white;
            color: #333;
            border: 1px solid #dee2e6;
        }
        .message-time {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
        }
        .session-item {
            padding: 15px;
            border-bottom: 1px solid #dee2e6;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .session-item:hover {
            background-color: #e9ecef;
        }
        .session-item.active {
            background-color: #007bff;
            color: white;
        }
        .session-item.active .session-product {
            color: rgba(255,255,255,0.8);
        }
        .session-product {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .session-merchant {
            font-size: 13px;
            color: #495057;
            margin-bottom: 5px;
        }
        .session-item.active .session-merchant {
            color: rgba(255,255,255,0.9);
        }
        .session-last-message {
            font-size: 12px;
            color: #6c757d;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .session-item.active .session-last-message {
            color: rgba(255,255,255,0.8);
        }
        .session-time {
            font-size: 11px;
            color: #6c757d;
            margin-top: 3px;
        }
        .session-item.active .session-time {
            color: rgba(255,255,255,0.7);
        }
        .unread-badge {
            background-color: #dc3545;
            color: white;
            border-radius: 10px;
            padding: 2px 8px;
            font-size: 11px;
            margin-left: 5px;
        }
        .session-item.active .unread-badge {
            background-color: rgba(255,255,255,0.9);
            color: #007bff;
        }
        .new-consultation-btn {
            margin: 15px;
            width: calc(100% - 30px);
        }
        .product-input-group {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container mt-4">
        <h2 class="mb-4">咨询商家</h2>
        
        <c:if test="${error != null}">
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                ${error}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </c:if>
        
        <div class="chat-container">
            <!-- 左侧会话列表 -->
            <div class="chat-sidebar">
                <button class="btn btn-primary new-consultation-btn" onclick="showNewConsultationModal()">新建咨询</button>
                <div id="sessionList">
                    <c:forEach var="session" items="${sessions}">
                        <div class="session-item" data-session-id="${session.sessionId}" 
                             data-product-name="${session.productName != null ? session.productName : '商品咨询'}" 
                             data-merchant-id="${session.merchantId}"
                             data-merchant-name="${session.merchant != null ? session.merchant.username : '未知商家'}"
                             onclick="loadSessionFromElement(this)">
                            <div class="session-product">
                                ${session.productName != null ? session.productName : '商品咨询'}
                                <c:if test="${session.unreadCountUser > 0}">
                                    <span class="unread-badge">${session.unreadCountUser}</span>
                                </c:if>
                            </div>
                            <div class="session-merchant">商家：${session.merchant != null ? session.merchant.username : '未知商家'}</div>
                            <div class="session-last-message">${session.lastMessage != null ? session.lastMessage : '暂无消息'}</div>
                            <div class="session-time">
                                <fmt:formatDate value="${session.lastMessageTime}" pattern="yyyy-MM-dd HH:mm"/>
                            </div>
                        </div>
                    </c:forEach>
                </div>
            </div>
            
            <!-- 右侧聊天区域 -->
            <div class="chat-main">
                <div class="chat-header">
                    <h5 id="chatTitle">请选择或创建咨询会话</h5>
                </div>
                <div class="chat-messages" id="chatMessages">
                    <div class="text-center text-muted mt-5">
                        <p>请选择左侧的咨询会话或创建新的咨询</p>
                    </div>
                </div>
                <div class="chat-input-area" id="chatInputArea" style="display: none;">
                    <div class="input-group">
                        <input type="text" class="form-control" id="messageInput" placeholder="输入消息...">
                        <button class="btn btn-primary" onclick="sendMessage()">发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 新建咨询模态框 -->
    <div class="modal fade" id="newConsultationModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新建咨询</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">商品名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="newProductName" placeholder="输入商品名称..." required>
                        <button type="button" class="btn btn-sm btn-outline-primary mt-2" onclick="searchMerchants()">搜索商家</button>
                    </div>
                    <div id="merchantList" style="display: none;">
                        <label class="form-label">选择商家 <span class="text-danger">*</span></label>
                        <div id="merchantOptions" class="list-group"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="createNewConsultation()" id="createBtn" disabled>创建</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        let ws = null;
        let currentSessionId = null;
        let currentProductName = null;
        let currentMerchantId = null;
        const userId = ${sessionScope.user.userId};
        const userType = 0; // 用户类型：0-用户，1-商家
        
        // 显示新建咨询模态框
        function showNewConsultationModal() {
            const modal = new bootstrap.Modal(document.getElementById('newConsultationModal'));
            modal.show();
        }
        
        let selectedMerchant = null;
        
        // 搜索商家
        function searchMerchants() {
            const productName = document.getElementById('newProductName').value.trim();
            if (!productName) {
                alert('请输入商品名称');
                return;
            }
            
            const merchantList = document.getElementById('merchantList');
            const merchantOptions = document.getElementById('merchantOptions');
            
            if (!merchantList || !merchantOptions) {
                console.error('找不到merchantList或merchantOptions元素');
                alert('页面元素加载错误，请刷新页面重试');
                return;
            }
            
            merchantOptions.innerHTML = '<div class="text-center p-3">搜索中...</div>';
            merchantList.style.display = 'block';
            merchantList.style.visibility = 'visible';
            
            // 查询商品信息获取商家列表
            fetch('${pageContext.request.contextPath}/client/consultation?action=searchProduct&name=' + encodeURIComponent(productName))
                .then(response => {
                    console.log('Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('返回的数据:', data);
                    console.log('merchantOptions元素:', merchantOptions);
                    
                    if (data.success && data.merchants && data.merchants.length > 0) {
                        merchantOptions.innerHTML = '';
                        console.log('商家数量:', data.merchants.length);
                        
                        data.merchants.forEach((merchant, index) => {
                            console.log('处理商家', index, ':', merchant);
                            
                            const item = document.createElement('div');
                            item.className = 'list-group-item list-group-item-action';
                            item.style.cursor = 'pointer';
                            
                            // 直接使用数据，简化处理
                            const merchantRealName = merchant.merchantRealName || '未设置名称';
                            const merchantName = merchant.merchantName || '未知账号';
                            
                            console.log('商家名称:', merchantRealName, '商家账号:', merchantName);

                            item.innerHTML = 
                                '<p class="mb-1"><strong>商家名称：</strong>' + merchantRealName + '</p>' +
                                '<p class="mb-1"><strong>商家账号：</strong>' + merchantName + '</p>';
                            
                            item.onclick = function() {
                                // 移除其他选中状态
                                merchantOptions.querySelectorAll('.list-group-item').forEach(i => {
                                    i.classList.remove('active');
                                });
                                item.classList.add('active');
                                selectedMerchant = merchant;
                                document.getElementById('createBtn').disabled = false;
                            };
                            
                            merchantOptions.appendChild(item);
                            console.log('已添加商家项到DOM');
                        });
                        
                        console.log('merchantOptions最终内容:', merchantOptions.innerHTML);
                    } else {
                        console.log('没有找到商家或数据格式不正确');
                        merchantOptions.innerHTML = '<div class="text-center p-3 text-muted">未找到该商品的商家</div>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    merchantOptions.innerHTML = '<div class="text-center p-3 text-danger">搜索失败，请重试</div>';
                });
        }
        
        // 创建新咨询
        function createNewConsultation() {
            if (!selectedMerchant) {
                alert('请先搜索并选择商家');
                return;
            }
            
            const merchantId = selectedMerchant.merchantId;
            const productId = selectedMerchant.productId;
            const productName = selectedMerchant.productName;
            const sessionId = userId + '_' + merchantId + '_' + productId;
            
            // 先创建会话记录
            fetch('${pageContext.request.contextPath}/client/consultation?action=createSession&sessionId=' + sessionId + 
                  '&productName=' + encodeURIComponent(productName) + 
                  '&productId=' + productId + 
                  '&merchantId=' + merchantId)
                .then(response => response.json())
                .then(createData => {
                    if (createData.success) {
                        // 创建成功后加载会话
                        loadSession(sessionId, productName, merchantId, null);
                        const modal = bootstrap.Modal.getInstance(document.getElementById('newConsultationModal'));
                        if (modal) {
                            modal.hide();
                        }
                        // 重置表单
                        document.getElementById('newProductName').value = '';
                        document.getElementById('merchantList').style.display = 'none';
                        document.getElementById('merchantOptions').innerHTML = '';
                        selectedMerchant = null;
                        document.getElementById('createBtn').disabled = true;
                        // 刷新页面以更新会话列表
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        alert('创建会话失败：' + (createData.message || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('创建会话失败:', error);
                    alert('创建会话失败，请重试');
                });
        }
        
        // 从元素加载会话
        function loadSessionFromElement(element) {
            const sessionId = element.getAttribute('data-session-id');
            const productName = element.getAttribute('data-product-name');
            const merchantId = element.getAttribute('data-merchant-id');
            const merchantName = element.getAttribute('data-merchant-name');
            loadSession(sessionId, productName, merchantId, merchantName, element);
        }
        
        // 加载会话
        function loadSession(sessionId, productName, merchantId, merchantName, element) {
            currentSessionId = sessionId;
            currentProductName = productName;
            
            // 从sessionId解析merchantId
            if (!merchantId) {
                const parts = sessionId.split('_');
                if (parts.length >= 2) {
                    merchantId = parts[1];
                }
            }
            currentMerchantId = merchantId;
            
            // 更新UI
            const title = merchantName ? productName + ' - ' + merchantName : productName;
            document.getElementById('chatTitle').textContent = title;
            document.getElementById('chatInputArea').style.display = 'block';
            
            // 更新会话列表选中状态
            document.querySelectorAll('.session-item').forEach(item => {
                item.classList.remove('active');
            });
            if (element) {
                element.classList.add('active');
            }
            
            // 连接WebSocket
            connectWebSocket();
            
            // 加载历史消息
            loadHistoryMessages();
        }
        
        // 连接WebSocket
        function connectWebSocket() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.close();
            }
            
            // 根据当前页面协议选择ws://或wss://
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = protocol + '//' + window.location.host + '${pageContext.request.contextPath}/chat/' + userId + '/' + userType + '/' + currentSessionId;
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                console.log('WebSocket连接已建立');
            };
            
            ws.onmessage = function(event) {
                const message = JSON.parse(event.data);
                handleMessage(message);
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
            };
            
            ws.onclose = function() {
                console.log('WebSocket连接已关闭');
            };
        }
        
        // 处理接收到的消息
        function handleMessage(message) {
            if (message.type === 'message') {
                displayMessage(message.content, message.senderType === 0 ? 'user' : 'merchant', new Date(message.createTime));
            } else if (message.type === 'ack') {
                console.log('消息发送成功:', message.messageId);
            } else if (message.type === 'error') {
                alert('错误：' + message.message);
            }
        }
        
        // 发送消息
        function sendMessage() {
            const content = document.getElementById('messageInput').value.trim();
            
            if (!content) {
                alert('请输入消息内容');
                return;
            }
            
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                alert('连接未建立，请稍候再试');
                return;
            }
            
            const message = {
                type: 'message',
                content: content,
                productId: currentSessionId.split('_')[2],
                productName: currentProductName
            };
            
            ws.send(JSON.stringify(message));
            
            // 显示自己发送的消息
            displayMessage(content, 'user', new Date());
            
            // 清空输入框
            document.getElementById('messageInput').value = '';
        }
        
        // 显示消息
        function displayMessage(content, senderType, time) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + senderType;
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = content;
            
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            timeDiv.textContent = formatTime(time);
            
            contentDiv.appendChild(timeDiv);
            messageDiv.appendChild(contentDiv);
            messagesDiv.appendChild(messageDiv);
            
            // 滚动到底部
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 加载历史消息
        function loadHistoryMessages() {
            if (!currentSessionId) {
                return;
            }
            fetch('${pageContext.request.contextPath}/client/consultation?action=history&sessionId=' + currentSessionId)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.messages) {
                        const messagesDiv = document.getElementById('chatMessages');
                        messagesDiv.innerHTML = '';
                        data.messages.forEach(msg => {
                            const msgTime = msg.createTime ? new Date(msg.createTime) : new Date();
                            displayMessage(msg.content, msg.senderType === 0 ? 'user' : 'merchant', msgTime);
                        });
                    }
                })
                .catch(error => {
                    console.error('加载历史消息失败:', error);
                });
        }
        
        // 格式化时间
        function formatTime(date) {
            if (!date || !(date instanceof Date)) {
                date = new Date();
            }
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return hours + ':' + minutes;
        }
        
        // 回车发送消息
        const messageInput = document.getElementById('messageInput');
        if (messageInput) {
            messageInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    sendMessage();
                }
            });
        }
    </script>
</body>
</html>

